package com.qingchunlin.blogsystem.controller;

import com.qingchunlin.blogsystem.common.utils.JWTUtils;
import com.qingchunlin.blogsystem.common.utils.SecurityUtils;
import com.qingchunlin.blogsystem.entity.Result;
import com.qingchunlin.blogsystem.entity.User;
import com.qingchunlin.blogsystem.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result<String> login(String userName, String password) {
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.failure("用户名或密码为空");
        }

        User user = userService.getUserByName(userName);
        if (user == null) {
            return Result.failure("没有此用户");
        }

        if (!SecurityUtils.verify(password, user.getPassword())) {
            return Result.failure("密码错误");
        }

        //验证成功,生成token进行返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userName", user.getUserName());
        String token = JWTUtils.createJWTToken(claims);

        return Result.success(token);
    }

    @RequestMapping("/getUserByToken")
    public User getUserByToken(HttpServletRequest httpServletRequest) {
        if (!StringUtils.hasLength(httpServletRequest.getHeader("user_token"))) {
            return null;
        }

        String token = httpServletRequest.getHeader("user_token");
        Integer userId = JWTUtils.getUserIdByToken(token);
        if (userId == null) {
            return null;
        }

        return userService.getUserById(userId);
    }


    @RequestMapping("/getAuthorByBlogId")
    public Result getAuthorByBlogId(Integer blogId) {
        if (blogId == null || blogId <= 0) {
            return Result.failure("无效blogId");
        }
        return Result.success(userService.getAuthorByBlogId(blogId));
    }

    @RequestMapping("/currentUserIsAuthor")
    public Result currentUserIsAuthor(Integer blogId, HttpServletRequest httpServletRequest) {
        if (blogId == null || blogId <= 0) {
            return Result.failure("无效blogId");
        }
        boolean currentUserIsAuthor = userService.currentUserIsAuthor(blogId, httpServletRequest.getHeader("user_token"));
        if (!currentUserIsAuthor) {
            return Result.failure("不是当前用户操作", false);
        }
       return Result.success(true);
    }
}
